package com.atguigu.flinkState;

import com.atguigu.been.WaterSensor;

import org.apache.flink.api.common.functions.MapFunction;

import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author wky
 * @create 2021-07-19-9:35
 */
//mapState 去重: 去掉重复的水位值. 思路: 把水位值作为MapState的key来实现去重, value随意
public class State_Keyed_MapState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();

        senv.setParallelism(1);
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(WaterSensor::getId);
        //mapState 去重: 去掉重复的水位值. 思路: 把水位值作为MapState的key来实现去重, value随意
        keyedStream.process(new KeyedProcessFunction<String, WaterSensor, String>() {
            //设置状态值
            private MapState<Integer,String> mapState;

            @Override
            public void open(Configuration parameters) throws Exception {
               mapState= getRuntimeContext().getMapState(new MapStateDescriptor<Integer, String>("map去重",Integer.class,String.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                if (!mapState.contains(value.getVc())){
                    mapState.put(value.getVc(),value.toString());
                    out.collect(mapState.get(value.getVc()));
                }

            }
        }).print();
        senv.execute();


    }
}
